﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class ExtractFile : MonoBehaviour
{
    float fileCount = 0;
    Slider slider = null;

    List<string> fileList = null;
    string filesText = null;

    void Awake()
    {
        slider = FindObjectOfType<Slider>();
        slider.value = 0;
        //----解压----
        Main.Http(Application.streamingAssetsPath + "/files.txt", GetFiles);
    }

    private void GetFiles(WWW www, string url)
    {
        filesText = www.text;
        string[] files = StringUtil.Split(www.text, "\r\n");
        fileList = new List<string>();
        for (int i = 0; i < files.Length; i++)
        {
            string file = files[i].Split('|')[0];
            if (!string.IsNullOrEmpty(file))
                fileList.Add(file);
        }
        www.Dispose();
        fileCount = fileList.Count;
        if (fileList.Count > 0)
            Main.Http(Application.streamingAssetsPath + fileList[0], Extract);
    }

    private void Extract(WWW www, string url)
    {
        url = url.Replace(Application.streamingAssetsPath, "");
        string fullUrl = Application.persistentDataPath + url;
        string directoryPath = Path.GetDirectoryName(fullUrl);
        if (!Directory.Exists(directoryPath))
            Directory.CreateDirectory(directoryPath);
        if (File.Exists(fullUrl))
            File.Delete(fullUrl);
        FileStream stream = File.Create(fullUrl);
        stream.Write(www.bytes, 0, www.bytes.Length);
        stream.Flush();
        stream.Dispose();
        www.Dispose();
        fileList.Remove(url);
        slider.value = (fileCount - fileList.Count) / fileCount;
        if (fileList.Count > 0)
            Main.Http(Application.streamingAssetsPath + fileList[0], Extract);
        else
            StartCoroutine(CreateFilesText());
    }

    private IEnumerator CreateFilesText()
    {
        yield return 0;
        StreamWriter sw = File.CreateText(Application.persistentDataPath + "/files.txt");
        sw.Write(filesText);
        sw.Flush();
        sw.Dispose();
        Scene scene = SceneManager.GetActiveScene();
        SceneManager.LoadScene(scene.name); 
    }

}
